"use strict";

const {
  app: electronApp,BrowserView, BrowserWindow } = require("electron");
const _ = require("lodash");
const path = require("path");
const CoreWindow = require("ee-core/electron/window");
const { getConfig} = require("ee-core/config");
const { isProd,isDev, getElectronDir, getUserHomeDir, getBaseDir} = require("ee-core/ps");
const { windowService } = require('../service/os/window');
const { isFileProtocol } = require('ee-core/utils');


// 创建 BrowserView
let view = null;

/**
 * 窗口功能控制器
 * @class
 */
class WindowController {
  //设置大小
  updateViewBounds() {
    const mainWindow = BrowserWindow.getFocusedWindow()
    if (view) {
      const { width, height } = mainWindow.getBounds()
      view.setBounds({ x: 145, y: 5, width: width-160, height: height-48 })
    }
  }
  //当前窗口打开browerview
  openBrowserView(url){
    const mainWindow = BrowserWindow.getFocusedWindow();
    if (!view) { 
      view = new BrowserView();
      view.webContents.on('did-finish-load', () => {
        view.webContents.insertCSS(`
          ::-webkit-scrollbar { width: 8px; }
          ::-webkit-scrollbar-track { background:rgb(165, 165, 165); }
          ::-webkit-scrollbar-thumb { background: #888; }
          ::-webkit-scrollbar-thumb:hover { background: #555;}
          `)
      }); 
      mainWindow.setBrowserView(view) 
      this.updateViewBounds();
       // 拦截新窗口打开，并在当前 BrowserView 中加载 URL
      view.webContents.setWindowOpenHandler(({ url }) => {
        view.webContents.loadURL(url) // 在当前 BrowserView 中加载 URL
        return { action: 'deny' } // 阻止新窗口打开
      })
      // 监听窗口大小变化
      mainWindow.on('resize',  this.updateViewBounds)
      mainWindow.on('maximize', this.updateViewBounds)
      mainWindow.on('unmaximize', this.updateViewBounds)
      mainWindow.on('restore', this.updateViewBounds)
      // 监听窗口关闭事件
      mainWindow.on('closed', () => {
        // 销毁 BrowserView
        view = null;
      });

    }else{
      console.log('have a views');
    }
    view.webContents.loadURL(url);
    view.webContents.on('did-finish-load', () => {
        console.log('Page loaded!',Date.now());
    });
  }
  //关闭窗口
  closeWindow(wcId=1) {
    let win = BrowserWindow.fromId(wcId);
    if (wcId && win) {
      win.close();
      return "success";
    } else{
      let win = CoreWindow.getMainWindow();
      win.close()
      return "No found wcId("+wcId+")!,but MainWindow closed!";
    }
  }
  //最小化窗口
  minimizeWindow(wcId=1) {    
    let win = BrowserWindow.fromId(wcId);
    if (wcId && win) { 
      win.minimize();
      return "success";
    } else { 
      let win = CoreWindow.getMainWindow();
      win.minimize()
      return "No found wcId("+wcId+")!,but MainWindow minimized!";
    }
  }

  //最大化窗口
  expandWindow(wcId=1) {
    let win = BrowserWindow.fromId(wcId);
    if (wcId && win) { 
      win.maximize();
      return "success";
    } else { 
      let win = CoreWindow.getMainWindow();
      win.maximize()
      return "No found wcId("+wcId+")!,but MainWindow maximized!";
    }
  }
    // 登录窗口控制器
  loginWindow(args) {
      
      const { width, height } = args;      
      const size = {
        width: width || 460,
        height: height || 700,
      };
      const win = CoreWindow.getMainWindow();
      win.hide(); //隐藏窗口，防止闪烁
      win.setSize(size.width, size.height);
      win.setResizable(false);
      win.center();
      win.show();
      win.focus();
  }
  
  // 打开主窗口
  mainWindow(args) {
    const { width, height } = args;
    const win = CoreWindow.getMainWindow();
    const size = {
      width: width || 980,
      height: height || 690,
    };
    win.hide();  //隐藏主窗口，防止闪烁
    setTimeout(() => {
      win.setSize(size.width, size.height);
      win.setResizable(true);
      win.center();
      win.show();
      win.focus();
    }, 100);
  }

  /**
   * 恢复窗口
   */
  restoreWindow() {
    const win = CoreWindow.getMainWindow();
    win.restore();
    const bounds = win.getBounds();
    return bounds;
  }

  getAllWindow() {     
    const windows = BrowserWindow.getAllWindows().map(function (item) {           
      return { id: item.id, title: item.title };
    });
    return CoreWindow.getMainWindow().id, windows;
  }
  /**
   * 打开新窗口
   */
  createWindow(args) {
    let winWcId = windowService.createWindow(args);
    return winWcId;
  }
  /**
   * 获取窗口contents id
   */
  getWCid(args) {
    // 主窗口的name默认是main，其它窗口name开发者自己定义
    const id = windowService.getWCid(args);
    return id;
  }

  //创建设置窗口
  openSettingWindow(args) {
    const { content } = args;
    let opt = {
        icon: path.join(getUserHomeDir(), "public/images/logo-32.png"),
        title: "软件设置",
        show: false, //先隐藏窗口，在加载完页面后再显示
        width: args.width||800,
        height: args.height||600,
        frame: false,   // 无边框
        resizable: false,
        autoHideMenuBar: true, 
        titleBarStyle: "hidden",
        titleBarOverlay:  { color:'#dddddd',symbolColor:'#000000',height: 26},
        closable: true,
        webPreferences : {
          devTools: isDev ? true : false,
          nodeIntegration: true,
          contextIsolation: false,  //是否启用上下文隔离
          // preload: path.join( getElectronDir(), 'preload', 'bridge.js'),
        }
      }
      
      const win = new BrowserWindow(opt);
      const winWcId = win.webContents.id;  
      let addr = 'http://localhost:8081';
      if (isProd()) {
          const { mainServer } = getConfig();
          if (isFileProtocol(mainServer.protocol)) {
            addr = mainServer.protocol + path.join(getBaseDir(), mainServer.indexPath);
          } else {
            addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
          }         
      } 
      let contentUrl = addr + content;
      win.loadURL( contentUrl );
      win.once("ready-to-show", () => {
        win.setTitle(opt.title);        
        win.focus();
        win.show();        
      });
      // 打开开发者工具
      // win.webContents.openDevTools(); 
      return winWcId;
  }

}

WindowController.toString = () => "[class WindowController]";
module.exports = WindowController;
